/***
 * 复杂的事情简单做
 * http://www.twinkling.cn/
 */
import './uploadPhoto.less';
import SelectPhoto from '../downdrop/photoAlbum';
import UploadThub from "../UploadThub/photo";
import {URL__} from '../../libs/Url';
import {MD5} from '../../libs/';
var useFilter = !!(document.documentElement.filters && document.documentElement.filters.item);
var isIE11 = document.documentMode === 11;


function uploadFile(file, opt) {
    opt = Object.assign({}, {
        uploadSuccess: item=> {
            console.log(item);
        },
        uploadFail: item=> {
        },
        uploading: item=> {

        },
    }, opt || {});
    let formData = new FormData();
    formData.append('file', file);
    /*AJAX上传部分*/
    const xhr = new XMLHttpRequest();
    xhr.open('POST', URL__.FUN_UPLOAD_ALBUM_PHOTO(file.albumid), true);
    xhr.onreadystatechange = () => {
        /*xhr finish*/
        try {
            if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
                const resp = JSON.parse(xhr.responseText);
                opt.uploadSuccess(resp)
            } else if (xhr.readyState == 4) {
                /*xhr fail*/
                const resp = JSON.parse(xhr.responseText);
                opt.uploadFail(resp)
            }
        } catch (e) {

        }
    };
    /*这里部分浏览器实现不一致，而且IE没有这个方法*/
    xhr.onprogress = xhr.upload.onprogress = progress => {
        opt.uploading(progress)
    };
    xhr.send(formData);
}


var on, off;
//v1.0.1 修复document.body未生成时，特征检测报错的bug
if (document.documentElement.addEventListener) {
    on = function (el, evt, fn) {
        el.addEventListener(evt, fn);
    };
    off = function (el, evt, fn) {
        el.removeEventListener.apply(el, Array.prototype.slice.call(arguments, 1));
    };
}
else {
    on = function (el, evt, fn) {
        el.attachEvent('on' + evt, fn);
    };
    off = function (el, evt, fn) {
        var args = Array.prototype.slice.call(arguments, 1);
        args[0] = 'on' + args[0];
        el.detachEvent.apply(el, args);
    };
}
var readPath = function (fileEl, index) {
    var src = fileEl.value || '';

    // IE11下，文档模式小于10无法通过value、getAttribute和outerHTML获取input[type=file]的真实路径
    if (src.search(/\w:\\fakepath/) === 0) {
        fileEl.select();
        src = document.selection.createRangeCollection()[index].htmlText;
    }
    console.log(src);
    return src;
};


var readAsDataURL = (file, target, index)=> {
    if (useFilter) {
        return readPath(target);
    }
    return new Promise((resolve, reject)=> {
        var key = `${MD5(file.name)}`;
        if (!!URL) {
            // 使用window.URL.createObjectURL提高性能
            resolve({
                key: key,
                url: URL.createObjectURL(file),
                name: file.name,
                file: file,
            });
        }
        else if (!window.FileReader) {
            // ff3.0不支持FileReader
            resolve({
                key: key,
                url: file.readAsDataURL(),
                name: file.name,
                file: file
            });
        }
        else {
            var fr = new window.FileReader();
            on(fr, 'load', function (e) {
                resolve({
                    key: key,
                    url: e.target.result,
                    name: file.name,
                    file: file
                });
            });
            fr.readAsDataURL(file);
        }
    });
};
export default React.createClass({
    getInitialState(){
        return {
            selected: {},
            // current: {},//当前选中的相册
            currentAlbum: {},
        }
    },
    componentWillReceiveProps(nextProps){
        const current = nextProps['current'];
        if (current && !_.isEmpty(current)) {
            this.setState({
                currentAlbum: current
            })
        }
    },
    readAsDataURL(file){
        if (useFilter) {
            return readAsDataURL(file);
        }
    },
    singleUpload(item, cb){
        const self = this;
        uploadFile(item.file, {
            uploading: progress=> {
                self.setState({
                    selected: Object.assign({}, self.state.selected, {
                        [item.key]: Object.assign({}, self.state.selected[item.key], {
                            progress: (progress.loaded / item.file.size) * 100 + '%'
                        })
                    })
                })
            },
            uploadSuccess: item_=> {
                self.setState({
                    selected: Object.assign({}, self.state.selected, {
                        [item.key]: Object.assign({}, self.state.selected[item.key], {
                            progress: '100%',
                            ...item_.result.data.image
                        })
                    })
                });
                _.delay(()=> {
                    self.setState({
                        selected: Object.assign({}, _.omit(self.state.selected, item.key))
                    }, ()=> {
                        cb();
                    });
                }, 300)
            }
        });
    },
    startUpload(){
        // 同步队列进行异步上传

        const self = this;
        if (_.isEmpty(self.state.currentAlbum) && self.props.list.length) {
            self.setState({
                currentAlbum: self.props.list[0]
            })
        }
        var selected = Object.keys(this.state.selected).reverse(), index = 0;
        selected.map(key=> {
            var item = self.state.selected[key];
            self.setState({
                selected: Object.assign({}, self.state.selected, {
                    [item.key]: Object.assign({}, self.state.selected[item.key], {
                        progress: '等待中...'
                    })
                })
            });
        });
        var exec = ()=> {
            if (index < selected.length) {
                var item = self.state.selected[selected[index]];
                item.file.albumid = self.state.currentAlbum.albumid;
                self.singleUpload(item, ()=> {
                    exec();
                })
            } else {
                console.log('同步队列进行异步上传结束')
            }
            index++;
        };
        exec();

    },
    render(){

        const self = this;
        const albums = self.props.list || [];
        return <div>
            <div className="upload-pic">
                <div className="choose-album">
                    <div className="text">上传到：</div>
                    <SelectPhoto
                        label={
                            self.state.currentAlbum.name ? self.state.currentAlbum.name :
                                (albums.length ? albums[0].name : '相册')
                        }
                        className="select"
                        img={self.state.currentAlbum.cover ? URL__.FUN_UPLOAD_PREVIEW(self.state.currentAlbum.cover) :
                            ((albums.length && albums[0].cover) ?
                                URL__.FUN_UPLOAD_PREVIEW(albums[0].cover) :
                                require('../../imgs/no-pic.png'))}>
                        {
                            albums.map((item, index)=> {
                                return <li key={index}>
                                    <a href="javascript:void(0);" onClick={()=> {
                                        self.setState({
                                            currentAlbum: item
                                        })
                                    }}>
                                        <img
                                            src={item.cover ? URL__.FUN_UPLOAD_PREVIEW(item.cover) :
                                                require('../../imgs/no-pic.png')}/>{item.name}
                                    </a>
                                </li>;
                            })
                        }

                    </SelectPhoto>
                </div>
                <div className="preview">
                    <div className="upload-list clearfix">
                        <ul className="clearfix">
                            {
                                Object.keys(self.state.selected).map((key, index) => {
                                    var file = self.state.selected[key];
                                    return <li key={index}>
                                        {
                                            file.progress ? <span>{file.progress}</span> : ''
                                        }
                                        <i className="fa fa-close"></i>
                                        <div className="pic">
                                            <img src={file.url || require('../../imgs/image1.jpg')}/>
                                        </div>
                                        <p>{file.name}</p>
                                    </li>;
                                })
                            }
                            {
                                Object.keys(this.state.selected).length ?
                                    <li className="add-img" style={{position: 'relative'}}>
                                        <input
                                            type="file"
                                            className="btn btn-info btn-lg"
                                            accept="image/*"
                                            style={{
                                                position: 'absolute',
                                                top: 0,
                                                left: 0,
                                                right: 0,
                                                width: '100%',
                                                opacity: 0, bottom: 0
                                            }}
                                            onChange={e=> {
                                                Promise
                                                    .all(Array.from(e.target.files)
                                                        .map((file, index)=> {
                                                            return readAsDataURL(file, e.target, index);
                                                        })
                                                    )
                                                    .then(results=> {
                                                        var tmp = {};
                                                        results.forEach(item=> {
                                                            tmp[item.key] = item;
                                                        });
                                                        self.setState({
                                                            selected: Object.assign(this.state.selected, tmp)
                                                        })
                                                    })
                                                    .catch(e=> {
                                                        console.log(e);
                                                    });

                                            }} multiple="true"/>
                                        <i>+</i>
                                        继续添加照片
                                    </li> : null
                            }
                        </ul>
                    </div>
                    {
                        !Object.keys(this.state.selected).length ?
                            <div className="upload-btn" style={{position: 'relative'}}>
                                <input type="button"
                                       style={{
                                           width: '100%',
                                       }}
                                       className="btn btn-info btn-lg" value="上传照片"/>
                                <input
                                    type="file"
                                    className="btn btn-info btn-lg"
                                    accept="image/*"
                                    style={{
                                        position: 'absolute',
                                        top: 0,
                                        left: 0,
                                        right: 0,
                                        width: '100%',
                                        opacity: 0
                                    }}
                                    onChange={e=> {
                                        Promise
                                            .all(Array.from(e.target.files)
                                                .map((file, index)=> {
                                                    return readAsDataURL(file, e.target, index);
                                                })
                                            )
                                            .then(results=> {
                                                var tmp = {};
                                                results.forEach(item=> {
                                                    tmp[item.key] = item;
                                                });
                                                self.setState({
                                                    selected: tmp
                                                })
                                            })
                                            .catch(e=> {
                                                console.log(e);
                                            });

                                    }} multiple="true"/>
                                <p style={{top: 'auto', width: '100%'}}>按住Ctrl可多选照片</p>
                            </div> : null
                    }

                </div>
            </div>
            <div className="modal-footer" style={{
                margin: '-18px'
            }}>
                <button className="btn btn-info btn-lg" onClick={()=> {
                    self.startUpload()
                }}>开始上传
                </button>
            </div>
        </div>
    }
})